package com.shine.icis.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.shine.esim.struts.webutil.SessionParam;
import com.shine.icis.blo.IDataSubmitService;
import com.shine.icis.blo.IETLContextVarService;
import com.shine.icis.blo.ISubmitConfService;
import com.shine.icis.config.SysCodeDictLoader;
import com.shine.icis.config.SysConstants;
import com.shine.icis.dto.ProgressStatus;
import com.shine.icis.exception.ICISException;
import com.shine.icis.hbean.ETLContextVar;
import com.shine.icis.hbean.SubmitLog;
import com.shine.icis.util.EFRameInf;
import com.shine.icis.dto.PfxBackInfo;

public class DataSubmitAction extends BaseAction {

	/**
	 * 生成报送文件
	 */
	private static final long serialVersionUID = 7638121893867812633L;
	
	private IDataSubmitService dataSubmitService;
	private IETLContextVarService etlContextVarService;
	private ISubmitConfService submitConfService;
	
	private String busiDate;//业务日期
	private String resubmitted;//是否重报
	private String increVersion;//是否升版本
	private String tr12Flag;//是否从源文件拷12个文件
	private String checkName;//核查点名称
	private String checkDate;//检查日期
	
	private SubmitLog submitLog;//报送日志
	private Map<String, String> etlContextVars;
//	private String currentBusiDate;//当前业务日期
	private String currentVersion;//当前内部版本号
	private String previousTradeDate;//上一个交易日
	private ProgressStatus progressStatus;
	private String downloadUrl;
	
	private String expA13Only;  //0：方案二，1：方案三
	private String expFileType;//默认生成文件方式:0从数据库导出；1从源目录拷贝
	
	private List<String> sendFileList;
	private int sendFileCount;
	private List<String> backFileList;
	private int backFileCount;
	private List<PfxBackInfo> pfxBackInfoList;
	
	public void setDataSubmitService(IDataSubmitService dataSubmitService) {
		this.dataSubmitService = dataSubmitService;
	}

	public void setEtlContextVarService(IETLContextVarService etlContextVarService) {
		this.etlContextVarService = etlContextVarService;
	}

	public void setSubmitConfService(ISubmitConfService submitConfService) {
		this.submitConfService = submitConfService;
	}

	public void setBusiDate(String busiDate) {
		this.busiDate = busiDate;
	}

	public void setResubmitted(String resubmitted) {
		this.resubmitted = resubmitted;
	}

	public void setIncreVersion(String increVersion) {
		this.increVersion = increVersion;
	}

	public void setTr12Flag(String tr12Flag) {
		this.tr12Flag = tr12Flag;
	}
	public String getTr12Flag() {
		return tr12Flag;
	}

	public void setCheckName(String checkName) {
		this.checkName = checkName;
	}
	public void setCheckDate(String checkDate) {
		this.checkDate = checkDate;
	}
	public SubmitLog getSubmitLog() {
		return submitLog;
	}
	
	public Map<String, String> getEtlContextVars() {
		return etlContextVars;
	}
//
//	public String getCurrentBusiDate() {
//		return currentBusiDate;
//	}

	public String getCurrentVersion() {
		return currentVersion;
	}
	
	public String getPreviousTradeDate() {
		return previousTradeDate;
	}
	
	public ProgressStatus getProgressStatus() {
		return progressStatus;
	}
	public String getDownloadUrl() {
		return downloadUrl;
	}
	
	public String getExpA13Only() {
		return expA13Only;
	}
	
	public String getExpFileType() {
		return expFileType;
	}

	public List<String> getSendFileList(){
		return sendFileList;
	}
	
	public int getSendFileCount(){
		return sendFileCount;
	}
	
	public List<String> getBackFileList(){
		return backFileList;
	}
	
	public int getBackFileCount(){
		return backFileCount;
	}
	
	public List<PfxBackInfo> getPfxBackInfoList(){
		return pfxBackInfoList;
	}
	
	private void initETLContextVar() {
		etlContextVars = new HashMap<String, String>();
		List<ETLContextVar> vars = etlContextVarService.getAllETLContextVar();
		for (ETLContextVar var : vars) {
			if ("BUSI_DATE".equals(var.getVarName())) {
				String tem = var.getVarValue();
				if (tem != null && tem.length() == 8) {
					StringBuffer date = new StringBuffer(tem);
					date.insert(6, "-").insert(4, "-");
					tem = date.toString();
				}
				etlContextVars.put("busiDate", tem);
			} else if ("INCREMENT".equals(var.getVarName())) {
				etlContextVars.put("increment", var.getVarValue());
			} else if ("OPERATOR".equals(var.getVarName())) {
				etlContextVars.put("autoRun", Boolean.toString(var.getVarValue() == null || var.getVarValue().trim().equals("")));
			} else if ("RUNNING".equals(var.getVarName())) {
				etlContextVars.put("running", var.getVarValue());
			} else if ("RUN_NOW".equals(var.getVarName())) {
				etlContextVars.put("runnow", var.getVarValue());
			} else if ("RUN_STEP".equals(var.getVarName())) {
				etlContextVars.put("runstep", var.getVarValue());
			}
		}
	}
	/**
	 * 进入“数据采集中心”页面
	 * @return
	 */
	public String initDataCollect() {
		initETLContextVar();
		
		boolean actived = etlContextVarService.getTaskServerActived();
		etlContextVars.put("actived", Boolean.toString(actived));//TaskServer是否活动
		
		String tem = SysCodeDictLoader.getInstance().getSubmitConfValue("RUN_SWITCH");
		if ("1".equals(tem)) {//自动运行开关处于启用状态
			tem = SysCodeDictLoader.getInstance().getSubmitConfValue("RUN_TIME");
		
			if (tem != null && tem.length() == 4) {
				StringBuffer date = new StringBuffer(tem);
				date.insert(2, ":");
				tem = date.toString();
			}
			etlContextVars.put("runTime", tem);//自动运行时点
		}
		ProgressStatus proSta = dataSubmitService.getProgressStatus();
		etlContextVars.put("jobStatus", Integer.toString(proSta.getDataColStatus()));
		
		etlContextVars.put("restartTaskServerEnalble", Boolean.toString(etlContextVarService.restartTaskServerEnalble()));
		
//		currentBusiDate = dataSubmitService.getBusiDate();
		previousTradeDate = submitConfService.getPreviousTradeDate();
		return success();
	}
	
	/**
	 * 重启TASKSERVER工具
	 * @return
	 */
	public String restartTaskServer() {
		boolean success = false;
		SessionParam user = (SessionParam)getSession().getAttribute(SysConstants.SESSION_USER_KEY);
		String userCode = user.getUSER_CODE();
		try {
			etlContextVarService.txRestartTaskServer();
//			TaskServerClient ser = new TaskServerClient("http://127.0.0.1:9089/icis_ts?wsdl");
//			ser.restartTaskServer();
			success = true;
			return success();
		} catch (ICISException e) {
			return error(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			return error();
		} finally {
			//记录系统日志
			EFRameInf.saveOpLog(userCode, EFRameInf.FUNCCODE_COLLECT, "重启采集服务", success);
		}
	}
	
	
	public String initCollectParams() {
		this.expA13Only = SysCodeDictLoader.getInstance().getSubmitConfValue("EXP_A13_ONLY");
		return success();
	}
	
	/**
	 * 设置手动采集参数
	 * @return
	 */
	public String configDataCollect() {
		if (busiDate == null) {
			return error("报送日期不能为空");
		}
		boolean success = false;
		SessionParam user = (SessionParam)getSession().getAttribute(SysConstants.SESSION_USER_KEY);
		String userCode = user.getUSER_CODE();
		try {
			busiDate = busiDate.trim().replaceAll("-", "");
			boolean loadTr12Flag = "Y".equals(tr12Flag);
			boolean actived = etlContextVarService.txResubmitConf(busiDate, loadTr12Flag, userCode);
			success = true;
			return success(actived ? "操作成功，已转入后台运行！" : "设置成功，请重启采集服务");
		} catch (ICISException e) {
			return error(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			return error();
		} finally {
			//记录系统日志
			EFRameInf.saveOpLog(userCode, EFRameInf.FUNCCODE_COLLECT, "采集数据，业务日期[" + busiDate + "]", success);
		}
	}
	
	/**
	 * 进入“报送数据生成”页面
	 * @return
	 */
	public String initDataGenerate() {
		initETLContextVar();
		
		ProgressStatus proSta = dataSubmitService.getProgressStatus();
		etlContextVars.put("jobStatus", proSta.getGenDataStatus() + ";" + proSta.getDataCheckStatus());//核对与生成数据一起处理
		
		return success();
	}
	
	/**
	 * 生成应用层数据
	 * @return
	 */
	public String dataGenerate() {
		boolean success = false;
		SessionParam user = (SessionParam)getSession().getAttribute(SysConstants.SESSION_USER_KEY);
		String userCode = user.getUSER_CODE();
		try {
			boolean actived = etlContextVarService.txDataGenerateConf(userCode);
			success = true;
			return success(actived ? "操作成功，已转入后台运行！" : "设置成功，请重启采集服务");
		} catch (ICISException e) {
			return error(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			return error(e.getMessage());
		} finally {
			//记录系统日志
			EFRameInf.saveOpLog(userCode, EFRameInf.FUNCCODE_GENDATA, "生成数据", success);
		}
	}
	
	/**
	 * 报送数据核对
	 * @return
	 */
	public String reCheckData() {
		boolean success = false;
		try {
			dataSubmitService.txCallCheckProc(checkName,checkDate);
			success = true;
			return success();
		} catch (ICISException e) {
			return error(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			return error(e.getMessage());
		} finally {
			//记录系统日志
			SessionParam user = (SessionParam)getSession().getAttribute(SysConstants.SESSION_USER_KEY);
			EFRameInf.saveOpLog(user.getUSER_CODE(), EFRameInf.FUNCCODE_CHECKDATA, "报送数据核对", success);
		}
	}
	/**
	 * 重新抽取法人数据
	 * @return
	 */
	public String reCollectData() {
		boolean success = false;
		try {
			dataSubmitService.txCallCheckProc(checkName, checkDate);
			success = true;
			return success();
		} catch (ICISException e) {
			return error(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			return error(e.getMessage());
		} finally {
			//记录系统日志
			SessionParam user = (SessionParam)getSession().getAttribute(SysConstants.SESSION_USER_KEY);
			EFRameInf.saveOpLog(user.getUSER_CODE(), EFRameInf.FUNCCODE_CHECKDATA, "法人数据重新抽取", success);
		}
	}
	/**
	 * 重新生成A13
	 * @return
	 */
	public String reGenRptA13() {
		boolean success = false;
		try {
			dataSubmitService.txCallCheckProc("A13_STD", checkDate);
			dataSubmitService.txCallCheckProc("A13_ANALYSE", checkDate);
			success = true;
			return success();
		} catch (ICISException e) {
			return error(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			return error(e.getMessage());
		} finally {
			//记录系统日志
			SessionParam user = (SessionParam)getSession().getAttribute(SysConstants.SESSION_USER_KEY);
			EFRameInf.saveOpLog(user.getUSER_CODE(), EFRameInf.FUNCCODE_COLLECT, "标准层数据A13重新生成", success);
			EFRameInf.saveOpLog(user.getUSER_CODE(), EFRameInf.FUNCCODE_GENDATA, "应用层数据A13重新生成", success);
		}
	}
	/**
	 * 进入“报送文件生成”页面
	 * @return
	 */
	public String initFileGenerate() {
		initETLContextVar();
		
		ProgressStatus proSta = dataSubmitService.getProgressStatus();
		etlContextVars.put("jobStatus", Integer.toString(proSta.getGenFileStatus()));
		
		if (proSta.getGenFileStatus() >= 1) {//已生成文件
			submitLog = dataSubmitService.getLastSubmitLog();
		}
		return success();
	}
	
	/**
	 * 生成报送文件
	 * @return
	 */
	public String fileGenerate() {
		boolean success = false;
		SessionParam user = (SessionParam)getSession().getAttribute(SysConstants.SESSION_USER_KEY);
		String userCode = user == null ? null : user.getUSER_CODE();//ETL调不需登入无用户信息
		try {
			Boolean resubmitFlag = resubmitted == null || resubmitted.trim().equals("") ? null : "Y".equals(resubmitted);
			Boolean increVerFlag = increVersion == null || increVersion.trim().equals("") ? null : "Y".equals(increVersion);
			Boolean copyTr12Flag = tr12Flag == null || tr12Flag.trim().equals("") ? null : "Y".equals(tr12Flag);
			dataSubmitService.txGeneratedFiles(userCode, resubmitFlag, increVerFlag, copyTr12Flag);
			success = true;
			return success();
		} catch (ICISException e) {
			return error(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			return error(e.getMessage());
		} finally {
			//记录系统日志
			EFRameInf.saveOpLog(userCode, EFRameInf.FUNCCODE_GENFILE, "生成报送文件", success);
		}
		
	}
	/**
	 * 进入“发送文件查询”页面
	 * @return
	 */
	public String initBackFileInfo() {
		return success();
	}
	/**
	 * 取得报送信息
	 * @return
	 */
	public String fileInfoGet() {
		boolean success = false;
		try {
			//取得pfx发送目录下的文件信息
			sendFileList = dataSubmitService.getPfxFileList("send");
			sendFileCount = sendFileList.size();
			backFileList = dataSubmitService.getPfxFileList("back");
			backFileCount = backFileList.size();
			pfxBackInfoList = dataSubmitService.getPfxBackInfo();
			success = true;
			return success();
		} catch (ICISException e) {
			return error(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			return error(e.getMessage());
		} 
	}
	
	/**
	 * 发送报送文件
	 * @return
	 */
	public String fileSend() {
		boolean success = false;
		SessionParam user = (SessionParam)getSession().getAttribute(SysConstants.SESSION_USER_KEY);
		String userCode = user == null ? null : user.getUSER_CODE();//ETL调不需登入无用户信息
		try {
			//取得pfx发送目录下的文件信息
			//sendFileList = dataSubmitService.getPfxFileList("send");
			//sendFileCount = sendFileList.size();
			dataSubmitService.txSendFiles(userCode);
			sendFileList = dataSubmitService.getPfxFileList("send");
			sendFileCount = sendFileList.size();
			success = true;
			return success();
		} catch (ICISException e) {
			return error(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			return error(e.getMessage());
		} finally {
			//记录系统日志
			EFRameInf.saveOpLog(userCode, EFRameInf.FUNCCODE_GENFILE, "发送报送文件", success);
		}
		
	}
	
	public String initGeneratedParams() {
		currentVersion = dataSubmitService.getCurrentVersion();
		this.expA13Only = SysCodeDictLoader.getInstance().getSubmitConfValue("EXP_A13_ONLY");
		this.expFileType = SysCodeDictLoader.getInstance().getSubmitConfValue("EXP_FILE_TYPE");
		ETLContextVar var = etlContextVarService.getETLContextVarByName("LOAD_TR12");
		this.tr12Flag = var != null ? var.getVarValue() : "";
		return success();
	}
	
	/**
	 * 下载报送文件
	 * @return
	 */
	public String fileDownload() {
		boolean success = false;
		try {
			downloadUrl = "/" + dataSubmitService.csCompressSubmitFiles();
			success = true;
			return success();
		} catch(ICISException e) {
			return error(e.getMessage());
		} catch(Exception e) {
			e.printStackTrace();
			return error();
		} finally {
			SessionParam user = (SessionParam)getSession().getAttribute(SysConstants.SESSION_USER_KEY);
			//记录系统日志
			EFRameInf.saveOpLog(user.getUSER_CODE(), EFRameInf.FUNCCODE_GENFILE, "下载报送文件", success);
		}
	}
	
	
	
	public String initQueryProcTrack() {
		initETLContextVar();
		progressStatus = dataSubmitService.getProgressStatus();
		return success();
	}
	
//	/**
//	 * 
//	 * @return
//	 */
//	public String initGeneratedFiles() {
//		etlContextVars = new HashMap<String, String>();
//		List<ETLContextVar> vars = etlContextVarService.getAllETLContextVar();
//		for (ETLContextVar var : vars) {
//			if ("BUSI_DATE".equals(var.getVarName())) {
//				String tem = var.getVarValue();
//				if (tem != null && tem.length() == 8) {
//					StringBuffer date = new StringBuffer(tem);
//					date.insert(6, "-").insert(4, "-");
//					tem = date.toString();
//				}
//				etlContextVars.put("busiDate", tem);
//			} else if ("INCREMENT".equals(var.getVarName())) {
//				etlContextVars.put("increment", var.getVarValue());
//			} else if ("RESUBMIT".equals(var.getVarName())) {
//				etlContextVars.put("resubmit", var.getVarValue());
//			} else if ("RUNNING".equals(var.getVarName())) {
//				etlContextVars.put("running", var.getVarValue());
//			}
//		}
//		boolean actived = etlContextVarService.getTaskServerActived();
//		etlContextVars.put("actived", Boolean.toString(actived));//TaskServer是否活动
//		
//		SubmitConf conf = submitConfService.getSubmitConfByCode("RUN_STRATEGY", SubmitConf.DATA_SUBMIT);
//		etlContextVars.put("runStrategy", conf.getValue());//自动运行方式
//		conf = submitConfService.getSubmitConfByCode("RUN_TIME", SubmitConf.DATA_SUBMIT);
//		String tem = conf.getValue();
//		
//		if (tem != null && tem.length() == 4) {
//			StringBuffer date = new StringBuffer(tem);
//			date.insert(2, ":");
//			tem = date.toString();
//		}
//		etlContextVars.put("runTime", tem);//自动运行时点
//		
//		previousTradeDate = submitConfService.getPreviousTradeDate();
//		return success();
//	}
}
